'''
Created on Feb 4, 2016

@author: JimmyMo
'''
from elasticsearch import Elasticsearch
from datetime import datetime
import json
import keyword
from searchresult import hit, searchresult

es_index = "icbcsou_index"
es_type_all = ""
es_type_raw = "icbcsou_raw"
es_type_html = "icbcsou_html"
es_type_file = "icbcsou_file"

def create_record(title, content, author, original_from, desc):
    article = {
    "title": str(title),
    "content": str(content),
    "author": str(author),
    "original_from": str(original_from),
    "desc": str(desc)
    }
    
    es = Elasticsearch()  # create a localhost server connection, or Elasticsearch("ip")
    es.create(index=es_index, doc_type=es_type_raw, body=json.dumps(article))

def _full_text_search(keyword):
    match_all = {
    "query": {
        "match": {
            "_all": str(keyword)
        }
    }}
    json_text = json.dumps(match_all)
    es = Elasticsearch()
    result = es.search(index=es_index, doc_type=es_type_all, body=json_text)
    return result

def full_text_search_results(keyword):
    results = _full_text_search(keyword)
    took = results['took']
    hits_json = results['hits']['hits']
    hits = [
                     hit(a['_index'],
                                  a['_type'],
                                  a['_id'],
                                  a['_score'],
                                  a['_source']['title'], 
                                  a['_source']['content'], 
                                  a['_source']['original_from']
                                  ) for a in hits_json]
    sr = searchresult(hits, took)
    return sr
#     return (hits, took)

def search_by_id(id, doc_type):
    es = Elasticsearch()
    a = es.get(index=es_index, id=id, doc_type=doc_type)
    sr = hit(a['_index'],
                      a['_type'],
                      a['_id'],
                      None,
                      a['_source']['title'], 
                      a['_source']['content'], 
                      a['_source']['original_from'])
    return sr
